<template>
  <div>
    <el-upload
      action=""
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :limit="1"
      :class="{disabed: fileList.length > 0 }"
      :http-request="onLoadImg"
      :before-upload="handleBeforeUpload"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog title="图片预览" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <el-progress v-if="ispercentage > 0" type="circle" :percentage="ispercentage" status="success"></el-progress>
  </div>
</template>

<script>
// 引入 SDK 包
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDlRwKUP3IUUK73tkombFi1DG4e3D9ra8R', // 秘钥
  SecretKey: '95MSN4XnuzxnlpkbJqLkEgwzpaUONRND'
})

export default {
  name: 'ImageUpload',
  components: {},
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      ispercentage: 0
    }
  },
  created() {},
  mounted() {},
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
      const index = this.fileList.findIndex(t => t.uid === file.uid)
      this.fileList.splice(index, 1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 图片上传
    onLoadImg(data) {
      const file = data.file
      cos.uploadFile({
        Bucket: 'lzs-1312685195', // 桶名称
        Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + file.name, // 文件名
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          this.ispercentage = progressData.percent * 100
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          this.fileList.push({ url: 'http://' + data.Location })
          console.log('上传成功', data)
        }
      })
    },
    // 图片上传之前的事件
    handleBeforeUpload({ type, size }) {
      if (!['image/png', 'image/jpg', 'image/jpeg', 'imagge/gif'].includes(type)) {
        this.$message.error('上传不是图片')
        return false
      }
      if (size > 5 * 1024 * 1024) {
        this.$message.error('上传图片太大')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  ::v-deep .disabed .el-upload--picture-card {
    display:none;

  }
  ::v-deep .disabed .el-upload {
    display:none;
  }
</style>
